package com.huang.auth.utils;

import com.huang.auth.entity.po.AuthMenuPO;
import com.huang.auth.entity.vo.RoutesVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HuangShen
 * @Description 菜单构造工具类
 * @create 2021-11-07 0:08
 */
public class MenuUtils {

    /**
     * 构造递归结构的 用户菜单
     *
     * @param authMenuByParentId authMenuByParentId
     * @param parentVO           parentVO
     * @param parentPO           parentPO
     */
    public static void creatRoutesChildren(Map<Long, List<AuthMenuPO>> authMenuByParentId, RoutesVO parentVO, AuthMenuPO parentPO) {

        List<AuthMenuPO> authMenuPOS = authMenuByParentId.get(parentPO.getId());
        if (CollectionUtils.isEmpty(authMenuPOS)) {
            return;
        }

        Set<RoutesVO> children = authMenuPOS.stream().map(authMenuPO -> {
            RoutesVO routesVO = new RoutesVO();
            RoutesVO.RouteMeta meta = routesVO.new RouteMeta();
            meta.setBadge(authMenuPO.getBadge());
            meta.setDot(authMenuPO.getDot());
            meta.setIcon(authMenuPO.getIcon());
            meta.setTitle(authMenuPO.getTitle());
            if (StringUtils.equalsIgnoreCase(authMenuPO.getName(), "index")) {
                meta.setNoClosable(true);
            }
            routesVO.setMeta(meta);
            routesVO.setComponent(authMenuPO.getComponent());
            routesVO.setName(authMenuPO.getName());
            routesVO.setPath(authMenuPO.getPath());
            routesVO.setSortValue(authMenuPO.getSortValue());
            creatRoutesChildren(authMenuByParentId, routesVO, authMenuPO);
            return routesVO;
        }).sorted().collect(Collectors.toCollection(LinkedHashSet::new));
        parentVO.setChildren(children);

    }
}
